package com.mhsoft.fenak.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONObject;

public class JSONParser {
	
	public static Object removeSpaces(Object object){
		String stringResult=object.toString().trim();
		for(int i=0;i<4;i++)
			if(stringResult.substring(i, i+1).equals("[") || stringResult.substring(i, i+1).equals("{")){
				stringResult=stringResult.substring(i);
				break;
			}
		return stringResult;
	}
	
	public static Object convertJSON2Hashmap(Object jObject) {
		try {
			if (jObject.getClass().equals(String.class) == true) {
				jObject = new JSONObject((String) jObject);
			}

			if (jObject.getClass().equals(JSONObject.class) == true) {
				HashMap<String, Object> result = new HashMap<String, Object>();
				// we have key value pairs
				@SuppressWarnings("rawtypes")
				Iterator iter = ((JSONObject) jObject).keys();
				while (iter.hasNext()) {
					String key = (String) iter.next();
					Object value = ((JSONObject) jObject).get(key);
					result.put(key, convertJSON2Hashmap(value));
				}
				return result;
			} 
			else if (jObject.getClass().equals(JSONArray.class) == true) {
				// we have an array list
				ArrayList<Object> result = new ArrayList<Object>();
				JSONArray jsonArray = (JSONArray) jObject;
				if (jsonArray != null) {
					for (int i = 0; i < jsonArray.length(); i++) {
						result.add(convertJSON2Hashmap(jsonArray.get(i)));
					}
				}
				return result;
			} else {
				return jObject.toString();

			}
		} catch (Exception e) {
			return jObject.toString();
		}
	}
}
